<script>
import TitleA from "@/comps/comm/TitleA.vue";
import EmpHolder from "@/pages/v1/mes/Flow/js/starter/EmpHolder.vue";
import QrCodeHolder from "@/pages/v1/mes/Flow/js/starter/QrCodeHolder.vue";
import apiFlow from "@/pages/v1/mes/Flow/js/apiFlow";
import formBuilder from "@/comps/form/formBuilder";
import EzData from "@/comps/EzData.vue";
import apiPaper from "@/pages/v1/mes/Paper/js/apiPaper";
import TitleAW from "@/comps/comm/TitleAW.vue";
import TitleB from "@/comps/comm/TitleB.vue";
import apiPlan from "@/pages/v1/mes/Plan/js/apiPlan";
import apiCheckTemplate from "@/pages/v1/mes/CheckTemplate/js/apiCheckTemplate";
import apiCheckTag from "@/pages/v1/mes/CheckTag/js/apiCheckTag";

export default {
  components: {TitleB, TitleAW, EzData, QrCodeHolder, EmpHolder, TitleA},
  data() {
    let fb = formBuilder()
    fb.setLabelPosition("right").setLabelWidth(70)
    // fb.addBlank("_blank2", "", 3)
    fb.addBlank("_blank1", "工序", 12)
    fb.addText("numSuccess", "成品", 4).setTextTypeNumber()
    fb.addText("numFail", "修品", 4).setTextTypeNumber()
    fb.addText("numWast", "废品", 4).setTextTypeNumber()
    fb.addBlank("_blank", "", 12)
    return {
      rowConfig: fb,
      emp: {name: "NA"},
      autoCalc: true,
      sn: "",
      plan: {sn: "", product: ""},
      checks: [],
      checkTags: [
        {id: 1, name: "成品", total: 0, tags: []},
        {id: 2, name: "修品", total: 0, tags: []},
        {id: 3, name: "焊品", total: 0, tags: []},
        {id: 4, name: "废品", total: 0, tags: []},
      ],
      checkProcess: 0,

      flow: null,
      curPaper: {
        processId: 0,
        flowId: 0,
        numSuccess: 0,
        numFail: 0,
        numWast: 0,
        empId: 0,
        srcPapers: [],
      },
      papers: [],
      // upperPapers: [],
      // upDateKey:"",
      curTab: 2,
    }
  },
  mounted() {
  },
  methods: {
    sumCheckTags(v) {
      //重新汇总数据
      for (let row of this.checkTags) {
        if (row.id === 1) {
          row.total = this.curPaper.numSuccess
        } else {
          row.total = 0
        }
        for (let tag of row.tags) {
          if (!tag.value) continue
          row.total += tag.value * 1
        }
        if (row.id > 1) {
          this.checkTags[0].total -= row.total
        }

      }
    },
    // createPaperLink(srcPaperId,numUse,processName){
    createPaperLink(paper) {
      return {
        srcPaperId: paper.id,
        numUse: paper.numSuccess - paper.numUsed,
        processName: paper.process.name,
        flowSn: paper.flow.sn,
      }
    },

    setEmp() {
      this.step = 1
      this.curPaper.empId = this.emp.id
    },
    setPlan(plan, code) {
      this.step = 2
      this.sn = code
      this.getPlan(code)
      this.getFlowPapers(code)
      this.getCheckTags(code)
    },
    getCheckTags(code){
      apiFlow.getCheckTags({code},res=>{
        this.checkTags = res.data
      })

    },
    getPlan(code) {
      let arr = code.split(".")
      if (arr.length > 0) {
        apiPlan.findBy({
          _where: {sn: arr[0]},
          _dumps: ["template",],
        }, res => {
          if (res.length > 0) {
            this.plan = res[0]
            if (this.plan.template && this.plan.template.checksIds.length > 0) {
              // this.getCheckTemplateByIds(this.plan.template.checksIds)
            } else {
              this.$toast.error("排产单未设置检验模版")
            }
          }
        })
      }
    },
    getCheckTemplateByIds(ids) {
      apiCheckTemplate.findBy({
        _where: {id__in: ids},
        _dumps: ["process", "checkProcess"],
      }, res => {
        this.checks = res
        //todo 暂时只考虑一个检验工序的检验
        if (this.checks.length > 0) {
          this.checkProcess = this.checks[0].checkProcessId
          this.getCheckTagsByCheckProcess(this.checks[0].checkProcessId, 1)
          this.getCheckTagsByCheckProcess(this.checks[0].checkProcessId, 2)
          this.getCheckTagsByCheckProcess(this.checks[0].checkProcessId, 3)
          this.getCheckTagsByCheckProcess(this.checks[0].checkProcessId, 4)
        }
      })
    },
    getCheckTagsByCheckProcess(checkProcess, groupId) {
      apiCheckTag.findBy({
        _where: {processId: checkProcess, groupId: groupId},
        limit: 0,
      }, res => {
        this.checkTags[groupId - 1].tags = res
      })

    },
    createNewPaper() {
      console.log(this.checkTags)
      let rebuildData = {
        code: this.sn,
        emp: this.emp.id,
        groups: []
      }
      for (let checkTag of this.checkTags) {
        let row = {
          id: checkTag.id,
          tags: []
        }
        for (let tag of checkTag.tags) {
          if (tag.value * 1 > 0) {
            row.tags.push({
              id: tag.id,
              value: tag.value,
            })
          }
        }
        rebuildData.groups.push(row)
      }
      apiFlow.checkSave(rebuildData, res => {
        this.$toast.info(res.message)
      })
    },
    getFlowPapers(code) {
      apiPaper.findBy({
        _where: {'flow.sn': code},
        _dumps: ["flow", "process"],
        _order: ["-id"],
        page: 1,
        limit: 10000
      }, res => {
        this.papers = res
        //找出第一个还有剩余量的Paper
        for (let paper of this.papers) {
          if (paper.numSuccess - paper.numUsed > 0) {
            this.curPaper = paper
            break
          }
        }
      })
    },
    setProcess(id) {
      this.curPaper.processId = id
    },

  },
  watch: {
    "curPaper.numFail"() {
      this.reCalcNum()
    },
    "curPaper.numWast"() {
      this.reCalcNum()
    },
  }


}
</script>

<template>
  <div class="pad5 flex-r flex-start">
    <div class="flex1">
      <div class="bcf round3">
        <div class="round3 pad5 marb5">
          <div class="flex-r">
            <div class="flex1 marr10 pad5 bcf bdso bdc04 bdw1 round3">
              <title-a>报工区</title-a>
              <div class="flex-r flex-end flex-fill">
                <div class="flex-start flex1">
                  <EmpHolder :emp.sync="emp" @update:emp="setEmp"></EmpHolder>
                </div>
                <div class="flex1">
                  <QrCodeHolder title="扫描跟踪单" @input="setPlan" key="plan"></QrCodeHolder>
                </div>
                <div class="flcc flex1">
                  <mu-button color="primary" @click="createNewPaper">
                    <mu-icon value="save"></mu-icon>
                  </mu-button>
                </div>
              </div>
              <div class="flrc bc13 padtb5">
                <div class="flex1">
                  <span>人员：</span>
                  <span>{{ emp.name }}</span>
                </div>
                <div class="flex1">
                  <span>产品：</span>
                  <span>{{ plan.product }}</span>
                </div>
                <div class="flex1">
                  <span>排产单：</span>
                  <span>{{ plan.sn }}</span>
                </div>
              </div>
              <div class="pad5">
                <!--                {{checkTags}}-->
                <div class="flex-r flex-wrap flex-start bcf marb10 pad5 round3">
                  <div class="pad5 bdso mar5 flrc round3"
                       :class="{'mdui-color-green flex1':item.id === 1,'mdui-color-cyan':item.id === 2,'mdui-color-orange':item.id === 3,'mdui-color-red':item.id === 4,}"
                       v-if="item.total > 0 || item.id === 1"
                       v-for="(item,index) in checkTags" :key="`row_${index}`">
                    <div class="fwb flrc bcf c11 pad3 marr5">
                      <span class="pad2 bcf fs8">{{ item.name }}：</span>
                      <span class="fs14 padr5">{{ item.total }}</span>
                    </div>
                    <div class="flrc" v-if="tag.value > 0" v-for="(tag,index) in item.tags" :key="`row_${index}`">
                      <span class=" bcf pad1 round3 c11">{{ tag.name }}</span>
                      <span class="fs8 padlr3"> x </span> <span class="fs14 fwb">{{ tag.value }}，</span>
                    </div>
                    <div class="flex1">&nbsp;</div>
                  </div>
                </div>

                <mu-tabs :value.sync="curTab" inverse>
                  <mu-tab :value="item.id" v-for="(item,index) in checkTags" :key="`row_1_${index}`">{{ item.name }}
                  </mu-tab>
                </mu-tabs>
                <div v-show="curTab === item.id" class="bcf pad5" v-for="(item,index) in checkTags"
                     :key="`row_${index}`">
                  <div class="flex-r flex-start flex-wrap pad5">
                    <div v-for="(tag,index) in item.tags" class="flrc" style="width: 10%" :key="`tag_${index}`">
                      <div class="fwb">{{ tag.name }}：</div>
                      <div>
                        <mu-text-field @input="sumCheckTags" style="width: 96px;" placeholder="输入数量" solo
                                       v-model.number="tag.value"></mu-text-field>
                      </div>
                    </div>
                    <div class="flex1">&nbsp;</div>
                  </div>
                  <div class="flrc bc13 padl5 marr5 fs14">
                    <div class="">{{ item.name }}合计：</div>
                    <div class="fwb ">
                      {{ item.total }}
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="bcf mart5 pad5 round3">
        <title-a>历史数据</title-a>
        <div v-if="papers.length > 0" class="pad3 mart10">
          <div class="flrc">
            <div class="flex1">工序</div>
            <div class="flex1">成品(用量)</div>
            <div class="flex1">修品</div>
            <div class="flex1">废品</div>
            <div class="flex1">时间</div>
          </div>
          <div class="flrc bdbso" v-for="(paper,index) in papers" :key="index">
            <div class="flex1" v-if="paper.process">{{ paper.process.name }}</div>
            <div class="flex1" v-else>--</div>
            <div class="flex1 flrc padtb5">
              <span class="flex1">{{ paper.numSuccess }}</span>
              <span class="flex1 c12">( {{ paper.numUsed }} )</span>
            </div>
            <div class="flex1">{{ paper.numFail }}</div>
            <div class="flex1">{{ paper.numWast }}</div>
            <div class="flex1">{{ $utils.str2time(paper.createAt) }}</div>
          </div>
        </div>
        <div class="mar10 pad20 bdda tac bc13" v-else>暂无数据</div>
      </div>
    </div>
  </div>
</template>

<style scoped>

</style>